import os
import sys
import django
import datetime
from dateutil.relativedelta import relativedelta

BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
print(os.path.abspath(__file__))
print(BASE_DIR)
sys.path.extend([BASE_DIR, ])
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "finance_c2c.settings")
django.setup()

from apps.coffee.models import CouponMakeEveryHour, CouponInfo, Channel
from django.contrib.auth import get_user_model

User = get_user_model()


def every_hour_make_coupon():
    now_time = datetime.datetime.now()
    print(now_time)
    queryset = CouponMakeEveryHour.objects.filter(end_time__gte=now_time, start_time__lte=now_time)

    for i in queryset:
        time_slot_list = i.time_slot.split(",")
        mapping_num_list = i.mapping_num.split(",")
        print(time_slot_list)
        print(mapping_num_list)
        channel_key = i.channel_key
        coupon_expire_time = i.coupon_expire_time
        expire_time = datetime.date.today() + relativedelta(days=coupon_expire_time)
        for k, current_time in enumerate(time_slot_list):
            if int(current_time) == now_time.hour:
                user = User.objects.get(mobile=channel_key)
                channel = Channel.objects.get(key=channel_key)
                coupon_queryset = CouponInfo.objects.filter(user=user, everyday_make=True, used=False)
                num = int(mapping_num_list[k])
                make_num = num - coupon_queryset.count()
                if make_num > 0:
                    CouponInfo.objects.bulk_create_by_normal(make_num, i.name, user, channel, expire_time,
                                                             now_time, i.c_type, quota=i.quota, everyday_make=True)
                # 更新没用完的券的有效期
                coupon_queryset.update(expire_time=expire_time, expired=False)


# def every_second_execute():
#     for i in range(20):
#         # 每十秒钟执行一次
#         every_hour_make_coupon()
#         time.sleep(3)


if __name__ == '__main__':
    every_hour_make_coupon()
